package mapred.example.model;

import java.util.Arrays;
import java.util.List;

import util.FieldUtil;

public class Paragraph {

    private int type;

    private List<String> text;

    private Paragraph(int type, String... text) {
        this.type = type;
        this.text = Arrays.asList(text);
    }

    public static Paragraph newInstanceFromParser(String s) {
        if (!s.isEmpty()) {
            if (s.startsWith("\t")) {
                s = s.substring(1);
            }

            if (s.endsWith("\t")) {
                s = s.substring(0, s.length() - 1);
            }

            int pos = s.indexOf('\t');
            int type = 0;
            try {
                type = Integer.parseInt(s.substring(0, pos));
            } catch (Exception e) {
                try {
                    type = Integer.parseInt(s.substring(0, 1));
                    pos = 0;
                } catch (Exception e2) {
                    type = 0;
                    pos = -1;
                }
            }
            return new Paragraph(type, s.substring(pos + 1).split("\t"));
        } else {
            return null;
        }
    }

    public int getType() {
        return type;
    }

    public List<String> getText() {
        return text;
    }

    public String getStr() {
        StringBuilder sb = new StringBuilder();
        sb.append(type);
        for (String t : text) {
            sb.append("\t");
            sb.append(t);
        }
        return sb.toString();
    }

    public long getLength() {
        return text.size();
    }

    public String toRLV(String[] query) {
        StringBuilder sb = new StringBuilder();
        sb.append("\2");
        sb.append(type);
        sb.append("\1");
        sb.append(text.size());
        for (String q : query) {
            List<Integer> poss = FieldUtil.getPositions(text, q);

            if (poss.size() > 0) {
                sb.append("\1");
                sb.append(q);
                sb.append("\t");
                sb.append(poss.size());
                for (int pos : poss) {
                    sb.append("\t");
                    sb.append(pos);
                    sb.append(" ");
                    sb.append("0");
                }
            }
        }
        return sb.toString();
    }

    public String encode() {
        StringBuilder sb = new StringBuilder();
        sb.append(type);
        sb.append("\t");
        sb.append(FieldUtil.encode(this.getText()));
        return sb.toString();
    }

}
